package cn.ibizlab.util.command;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.data.domain.Page;
import org.springframework.util.ObjectUtils;
import java.util.ArrayList;
import java.util.List;

@NoArgsConstructor
@Accessors(chain = true)
@JsonIgnoreProperties(value = "handler",ignoreUnknown = true)
public class ExecutionResult<T> {

    @Getter
    @Setter
    private int status = 200;

    @Getter
    @Setter
    private String message;

    @Getter
    @Setter
    private T body;

    @Getter
    private String code;

    private List list;

    public  static <T> ExecutionResult<T> ok(T body) {
        ExecutionResult<T> result = new ExecutionResult<>();
        result.status = 200;
        result.body=body;
        return result;
    }

    public static <T> ExecutionResult<T> error(String message,String... args) {
        return error(500,message,args);
    }

    public static <T> ExecutionResult<T> error(int status,String message,String... args) {
        ExecutionResult<T> result = new ExecutionResult<>();
        result.status = status;
        result.message=String.format(message,args);
        return result;
    }

    @JsonIgnore
    @JSONField(serialize = false)
    public boolean isSuccess() {
        return (status == 200 && ObjectUtils.isEmpty(code)) || "200".equals(code);
    }

    @JsonIgnore
    @JSONField(serialize = false)
    public boolean isError() {
        return !isSuccess();
    }

    public List getList()
    {
        if(body!=null)
        {
            if(body instanceof Page)
                return ((Page<?>) body).getContent();
            else if (body instanceof List)
                return (List)body;
            else if (list != null)
                return list;
        }
        return new ArrayList();
    }
}
